import React, { useState } from 'react';
import { FloatButton, Drawer, Card, Space, Button, Tag, Typography, Divider } from 'antd';
import { UserOutlined, SafetyCertificateOutlined, BugOutlined } from '@ant-design/icons';
import { useAuthStore } from '../../stores/auth';

const { Text, Paragraph } = Typography;

// 预定义的角色和权限
const PRESET_ROLES = {
  admin: {
    name: '系统管理员',
    roles: ['admin', 'user'],
    permissions: [
      'user:read', 'user:create', 'user:update', 'user:delete',
      'role:read', 'role:create', 'role:update', 'role:delete',
      'permission:read', 'permission:create', 'permission:update', 'permission:delete',
      'system:read', 'system:update',
      'dashboard:read',
      'profile:read', 'profile:update'
    ]
  },
  manager: {
    name: '部门经理',
    roles: ['manager', 'user'],
    permissions: [
      'user:read', 'user:update',
      'role:read',
      'permission:read',
      'dashboard:read',
      'profile:read', 'profile:update'
    ]
  },
  user: {
    name: '普通用户',
    roles: ['user'],
    permissions: [
      'dashboard:read',
      'profile:read', 'profile:update'
    ]
  },
  guest: {
    name: '访客',
    roles: ['guest'],
    permissions: [
      'dashboard:read'
    ]
  }
};

const DevTools: React.FC = () => {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const { user, updateUser, logout } = useAuthStore();
  
  // 只在开发环境下显示
  if (import.meta.env.PROD) {
    return null;
  }

  const switchRole = (roleKey: string) => {
    const roleConfig = PRESET_ROLES[roleKey as keyof typeof PRESET_ROLES];
    if (roleConfig && user) {
      const updatedUser = {
        ...user,
        roles: roleConfig.roles,
        permissions: roleConfig.permissions,
        updateTime: new Date().toISOString(),
      };
      
      updateUser(updatedUser);
      console.log(`🔄 已切换到角色: ${roleConfig.name}`, updatedUser);
    }
  };

  const resetToDefault = () => {
    logout();
    console.log('🔄 已重置用户状态，下次访问将自动模拟登录');
  };

  return (
    <>
      <FloatButton
        icon={<BugOutlined />}
        tooltip="开发工具"
        type="primary"
        style={{ right: 24, bottom: 24 }}
        onClick={() => setDrawerVisible(true)}
      />
      
      <Drawer
        title={
          <Space>
            <BugOutlined />
            <span>开发工具</span>
            <Tag color="orange">DEV</Tag>
          </Space>
        }
        placement="right"
        width={400}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          {/* 当前用户信息 */}
          <Card size="small" title={<Space><UserOutlined />当前用户</Space>}>
            {user ? (
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>
                  <Text strong>用户名：</Text>
                  <Text>{user.username}</Text>
                </div>
                <div>
                  <Text strong>邮箱：</Text>
                  <Text>{user.email}</Text>
                </div>
                <div>
                  <Text strong>角色：</Text>
                  <div style={{ marginTop: 4 }}>
                    {user.roles?.map(role => (
                      <Tag key={role} color="blue">{role}</Tag>
                    ))}
                  </div>
                </div>
                <div>
                  <Text strong>权限数量：</Text>
                  <Text>{user.permissions?.length || 0}</Text>
                </div>
              </Space>
            ) : (
              <Text type="secondary">未登录</Text>
            )}
          </Card>

          {/* 角色切换 */}
          <Card size="small" title={<Space><SafetyCertificateOutlined />角色切换</Space>}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Paragraph>
                <Text type="secondary">
                  快速切换不同角色以测试权限功能
                </Text>
              </Paragraph>
              
              <Space direction="vertical" style={{ width: '100%' }}>
                {Object.entries(PRESET_ROLES).map(([key, config]) => (
                  <Button
                    key={key}
                    block
                    onClick={() => switchRole(key)}
                    type={user?.roles?.includes(key) ? "primary" : "default"}
                  >
                    切换到 {config.name}
                    <br />
                    <Text style={{ fontSize: 12 }}>
                      {config.permissions.length} 个权限
                    </Text>
                  </Button>
                ))}
              </Space>
            </Space>
          </Card>

          {/* 权限列表 */}
          {user && (
            <Card size="small" title="当前权限列表">
              <div style={{ maxHeight: 200, overflow: 'auto' }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  {user.permissions?.map(permission => (
                    <Tag key={permission} color="green" style={{ margin: 2 }}>
                      {permission}
                    </Tag>
                  ))}
                </Space>
              </div>
            </Card>
          )}

          <Divider />

          {/* 操作按钮 */}
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button 
              danger 
              block 
              onClick={resetToDefault}
            >
              重置用户状态
            </Button>
            
            <Button 
              block 
              onClick={() => {
                console.log('当前用户状态：', user);
                console.log('当前环境：', import.meta.env.MODE);
                console.log('可用角色：', Object.keys(PRESET_ROLES));
              }}
            >
              打印调试信息
            </Button>
          </Space>

          <Card size="small" title="使用说明">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Text>• 此工具仅在开发环境下可见</Text>
              <Text>• 可以快速切换不同角色测试权限</Text>
              <Text>• 所有操作会在控制台输出日志</Text>
              <Text>• 重置后需要刷新页面重新自动登录</Text>
            </Space>
          </Card>
        </Space>
      </Drawer>
    </>
  );
};

export default DevTools; 